from . import login_blueprint
from flask import request, render_template, redirect, url_for
from ..config.WXConfig import WxConfig
import uuid
from ..utils.common import get_qr_code, set_response
import time
from .. import db
from ..models.tables import LoginCode, User
from ..config.config import CodeMap
from flask_login import logout_user, login_user


@login_blueprint.route('/login')
def login():
    before = request.args.get("next") or '/';
    ids = str(uuid.uuid1())
    uri = WxConfig.redirect_uri + '?uuid=' + ids
    re_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + WxConfig.appID + '&redirect_uri=' + uri + '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
    qr_code = get_qr_code(re_url, ids)
    print(time.time())
    login_code = LoginCode(uuid=ids, qrcode=qr_code, create_at=str(int(time.time() * 1000)), status=0)
    db.session.add(login_code)
    db.session.commit()
    return render_template('login/login.html', url=qr_code, uuid=ids, next_url=before)


@login_blueprint.route('/login.do', methods=['POST'])
def do_login():
    username = request.form['username']
    password = request.form['password']
    print(username)
    print(password)
    if username is None or password is None:
        return set_response(CodeMap.PARAMS_ERROR, CodeMap.PARAMS_ERROR_MSG, None)
    user = User.query.filter_by(username=username, password=password).first()
    if user:
        login_user(user, remember=False)
        data = {'uid': user.id}
        return set_response(CodeMap.SUCCESS, CodeMap.SUCCESS_MSG, data)
    else:
        return set_response(CodeMap.LOGIN_ERROR, CodeMap.LOGIN_ERROR_MSG, None)


@login_blueprint.route('/logout.do')
def do_logout():
    logout_user()
    return redirect(url_for('login.login'))